package sjg.tenNormalAlgorithm.kmp;

/**
 * 暴力匹配例子，为了引入KMP算法
 */
public class ViolenceMatch {
    public static void main(String[] args) {
        String s1 = "aabcd";
        String s2 = "ab";
        int i = violenceMatch2(s1, s2);
        System.out.println("匹配到的索引值为：" + i);
    }

    /**
     * 暴力匹配 写法2 - hsp
     */
    private static int violenceMatch2(String str1, String str2) {
        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = s1.length;
        int s2Len = s2.length;

        int j = 0; // i索引指向s1
        int i = 0; // j索引指向s2
        while (i < s1Len && j < s2Len) {// 保证下标不越界
            // 匹配OK
            if (s1[i] == s2[j]) {
                i++;
                j++;
            } else { // 匹配不OK
                // 如果失配，还原值
                i = i - (j - 1); // 还原i值
                j = 0; // 还原j值
            }
        }

        // 判断是否匹配成功
        if (j == s2Len) {
            return i - j;
        } else {
            return -1;
        }
    }

    /**
     * 暴力匹配 写法1
     */
    private static int violenceMatch(String s1, String s2) {
        for (int i = 0; i + s2.length() <= s1.length(); i++) {
            boolean flag = true;
            for (int j = 0; j < s2.length(); j++) {
                if (s2.charAt(j) != s1.charAt(i + j)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return i;
            }
        }
        return 0;
    }
}
